<?php

require_once 'ActionFramework/start.php';

class AdminAction extends Action {
	
	// No fields required
	
	public function trigger($request) {
		
		$admin = $_SESSION['user'];
		
		global $DB;
		$users = $DB->get_all_users();
		$newsletter_addresses = $DB->get_all_newsletter_addresses();
		
		
		$signed_up_recently = 0;
		$active_recently = 0;	
			
		$recently = new Date();
		$recently->addMonths(-3); // 3 months is recently
		
		$messages_recently = $DB->messages_sent_since($recently);
		
		$languages = array();
		$messages_sent = array();
		
		foreach ($users as $user) {
			$messages_sent[$user->user_id] = $DB->messages_sent_by_user_since($user, $recently);
			
			if ($user->signup_date->after($recently)) {
				$signed_up_recently += 1;
			}
			if ($user->last_login->after($recently)) {
				$active_recently += 1;
			}
			
			foreach ($user->known_languages as $lang_code) {
				if (!isset($languages[$lang_code])) {
					$languages[$lang_code] = array('known' => 0, 'unknown' => 0);
				}
				$languages[$lang_code]['known'] += 1;
			}
			
			foreach ($user->unknown_languages_and_levels as $comb) {
				$lang_code = $comb[0];
				if (!isset($languages[$lang_code])) {
					$languages[$lang_code] = array('known' => 0, 'unknown' => 0);
				}
				$languages[$lang_code]['unknown'] += 1;
			}
		}
		
		// Sort languages
		$tmp = array_map('array_sum', $languages);
		asort($tmp);
		$lang_order = array_keys(array_reverse($tmp));
		$languages_sorted = array();
		foreach ($lang_order as $lang_code) {
			$languages_sorted[$lang_code] = $languages[$lang_code];
		}		
		
		$couples_possible = $DB->couples_possible();
		
		$statistics = array(
			'signed_up_recently' => $signed_up_recently, 
			'active_recently' => $active_recently, 
			'messages_recently' => $messages_recently, 
			'couples_possible'=> $couples_possible,
			'languages_summary' => $languages_sorted
		);
		
		return new AdminView($admin, $users, $messages_sent, $newsletter_addresses, $statistics);	
	}
	
}

?>